from rest_framework import serializers
from .models import  Absent,AbsentType,AbsentStatusChoices
from apps.oaauth.serializers import UserSerializer #导入用户的序列化器
from rest_framework import exceptions

#请假类型这个字段应该是只读的
#回复给后端和数据库时只能返回id，而不是用户自定义，所以需要使用序列化嵌套
class AbsentTypeSerializer(serializers.ModelSerializer): #对请假类型进行序列化
    class Meta:
        model = AbsentType
        fields = '__all__'

class AbsentSerializer(serializers.ModelSerializer):  #对请假模型进行序列化
    absent_type = AbsentTypeSerializer(read_only=True) #只读字段,该字段为请假种类的实例
    absent_type_id = serializers.IntegerField(write_only=True)
    #read_only :只会在讲ORM模型序列化成字典时才会将这个字段序列化
    #write_only:只会在将data进行校验时才会用到
    requester = UserSerializer(read_only=True)#发起人也做序列化嵌套
    responder = UserSerializer(read_only=True) #审批人做序列化嵌套
    class Meta:
        model = Absent
        fields = '__all__'

    #验证absent_type_id在数据库是否存在
    def validate_absent_type_id(self, value): #value是用户上传的id
        if not AbsentType.objects.filter(pk=value).exists():
            raise exceptions.ValidationError("考勤类型不存在！")
        return value

    #重写方法
    def create(self,validated_data): #前端上传的数据
        request = self.context['request']

        user = request.user #获取当前登录用户
        #获取审批者
        #1.如果是部门leader
        if user.department.leader.uid == user.uid:
            if user.department.name =='董事会':
                responder = None   #董事会老大没有审批者
            else:
                responder = user.department.manager #部门老大审批人就是董事会负责人
        #2.不是部门leader
        else:
            responder = user.department.leader  #部门员工审批人为部门老大

        #董事会老大请假直接通过
        if responder is None:
            validated_data['status'] = AbsentStatusChoices.PASS
        else: #其他人默认状态为审核中
            validated_data['status'] = AbsentStatusChoices.AUDITING
        absent = Absent.objects.create(**validated_data,requester=user,responder=responder)
        return  absent

    #重写方法
    def update(self, instance, validated_data):  #代表一个Absent模型实例（一个具体的请假对象）
        if instance.status != AbsentStatusChoices.AUDITING:  #检查状态是否审核中，不是就不能修改
            raise exceptions.APIException(detail='不能修改已经确定的请假数据！')
        request = self.context['request']
        user = request.user #获取当前登录的用户
        if instance.responder.uid != user.uid:  #用户非审批者不能修改
            raise exceptions.AuthenticationFailed(detail='您无权处理该考勤！')
        instance.status = validated_data['status'] #更新请假状态
        instance.response_content = validated_data['response_content']
        instance.save()
        return instance

